package com.txhy.certificatechain.ui.fragment.bottomnavigation;

import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.txhy.certificatechain.R;
import com.txhy.certificatechain.model.bean.MailListBean;
import com.txhy.certificatechain.model.bean.UserBean;
import com.txhy.certificatechain.presenter.friend.FriendListPresenter;
import com.txhy.certificatechain.ui.activity.base.BaseFragment;
import com.txhy.certificatechain.ui.adapter.ContactsAdapter;
import com.txhy.certificatechain.ui.view.friend.FriendListView;
import com.txhy.certificatechain.ui.widget.LetterIndexView;
import com.txhy.certificatechain.utils.CommUtils;
import com.txhy.certificatechain.utils.GsonUtil;
import com.txhy.certificatechain.utils.PrefUtil;
import com.txhy.certificatechain.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2018-2030, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: FriendListFragment.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述: 好友列表--底部导航
 * 创建时间: 2018/9/20 10:24
 * 更新时间：2018/9/20 10:24
 * -----------------------------------------------------------------
 * 2018/9/20 10:24: 创建 FriendListFragment.java (侯建军);
 * -----------------------------------------------------------------
 */
public class FriendListFragment extends BaseFragment<FriendListView,FriendListPresenter> implements LetterIndexView.onWordsChangeListener, AbsListView.OnScrollListener,FriendListView {
    @BindView(R.id.lv_list)
    ListView lv_list;

    @BindView(R.id.liv_az)
    LetterIndexView liv_az;
    @BindView(R.id.tv)
    TextView tv;

    @BindView(R.id.ed_souSuo)
    EditText ed_souSuo;

    @BindView(R.id.ll_dialog)
    LinearLayout ll_dialog;
    @BindView(R.id.ll_noData)
    LinearLayout ll_noData;
    @BindView(R.id.tv_noData)
    TextView tv_noData;

    private ContactsAdapter contactsAdapter;//加载的列表的
    private Pattern p;                      //用来判断输入的是引文还是字符串
    private Matcher m;                      //用来判断输入的是引文还是字符串
    private List<MailListBean.DataEntity> peopleList = new ArrayList<>();   //联系人列表
    private List<MailListBean.DataEntity> listList = new ArrayList<>();     //加载中的列表
    private Handler handler;

    private UserBean.DataEntity.MapEntity user;
    @Override
    protected FriendListPresenter createPresenter() {
        return new FriendListPresenter();
    }

    public static FriendListFragment newInstance() {
        return new FriendListFragment();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_mail_list;
    }


    @Override
    public void initView(View rootView) {
        super.initView(rootView);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(PrefUtil.getLoginBoolean(getActivity())){
            user= PrefUtil.getUserBean(getActivity());
            mPresenter.getMailMsg(user.getId()+"");
        }
    }

    /**
     * 初始化滚动监听
     */
    public void initScrollListener() {
        super.initListener();
        ed_souSuo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = (ed_souSuo.getText().toString()).trim();
                listList.clear();
                if (text.isEmpty()) {
                    listList.addAll(peopleList);
                    contactsAdapter.notifyCheck(listList);
                    liv_az.setVisibility(View.VISIBLE);
                } else {
                    liv_az.setVisibility(View.GONE);
                    p = Pattern.compile("[a-zA-Z]");
                    m = p.matcher(text);
                    if (m.matches()) {//输入的是英文大写
                        for (int i = 0; i < peopleList.size(); i++) {
                            if ((peopleList.get(i).namePinYin.toUpperCase()).indexOf(text.toUpperCase()) != -1) {
                                listList.add(peopleList.get(i));
                            }
                        }

                    } else {//字符串的判断
                        for (int i = 0; i < peopleList.size(); i++) {
                            if (peopleList.get(i).getCardName().indexOf(text) != -1) {
                                listList.add(peopleList.get(i));
                            }

                        }
                    }
                    contactsAdapter.notifyCheck(listList);
                }


            }
        });

        handler = new Handler();
        liv_az.setOnWordsChangeListener(this);
        lv_list.setOnScrollListener(this);
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//                Intent intent=new Intent(getActivity(), FriendInforActivity.class);
//                Bundle bundle=new Bundle();
//                bundle.putSerializable("bean",peopleList.get(position));
//                intent.putExtra("bean",bundle);
//                startActivity(intent);
            }
        });
    }

    @OnClick({ R.id.img_dialogClose, R.id.tv_quxiao, R.id.tv_queren,R.id.ll_dialog})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_dialogClose:
                ll_dialog.setVisibility(View.GONE);
                break;
            case R.id.tv_quxiao:
                ll_dialog.setVisibility(View.GONE);
                break;
            case R.id.tv_queren:
//                    Intent intent = new Intent();
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("list", (Serializable) heardleList);
//                    intent.putExtra("list", bundle);
//                    setResult(1, intent);
//                    finish();
                break;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        //当滑动列表的时候，更新右侧字母列表的选中状态
        liv_az.setTouchIndex(peopleList.get(firstVisibleItem).getFirstLetter());
    }

    @Override
    public void wordsChange(String words) {
        updateWord(words);
        updateListView(words);
    }

    private void updateWord(String words) {
        tv.setText(words);
        tv.setVisibility(View.VISIBLE);
        //清空之前的所有消息
        handler.removeCallbacksAndMessages(null);
        //1s后让tv隐藏
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tv.setVisibility(View.GONE);
            }
        }, 500);
    }

    /**
     * 选中了字母索引列表的任何一个字母，ListView相应的字母也得置顶
     *
     * @param words
     */
    private void updateListView(String words) {
        for (int i = 0; i < peopleList.size(); i++) {
            if (words.equals(peopleList.get(i).firstLetter)) {
                lv_list.setSelection(i);
                return;
            }
        }
    }

    @Override
    public void getMailSuccess(String msg) {
        ll_noData.setVisibility(View.GONE);
        MailListBean bean= GsonUtil.GsonToBean(msg,MailListBean.class);
        //在这里对联系人集合进行排序
        for (int i =0;i<bean.getData().size();i++){
            bean.getData().get(i).setNamePinYin("设置拼音");
            bean.getData().get(i).setFirstLetter("设置首字母");
        }
        peopleList.clear();
        listList.clear();
        peopleList.addAll(bean.getData());
        CommUtils.sortList(peopleList);
        listList.addAll(peopleList);
        contactsAdapter = new ContactsAdapter(getActivity(), listList);
        lv_list.setAdapter(contactsAdapter);
        initScrollListener();
    }

    @Override
    public void getMailFail(String msg) {
        ToastUtil.showLong(getActivity(),msg);
    }

    @Override
    public void getNoData(String msg) {
        ll_noData.setVisibility(View.VISIBLE);
        tv_noData.setText("您还没有任何好友哦！");
    }
}

